# _*_ coding:utf-8 _*_
# @author : Joyamon
# @time : 2022-10-10 16:47
# @file : baidu_translate.py


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time


def search_baidu():
    return input("百度翻译为您提供服务，请输入要翻译的单词（句子）：")


class Baidu:
    def __init__(self):
        # 设置成无头浏览器
        chrome_option = Options()
        chrome_option.add_argument('--headless')
        self.driver = webdriver.Chrome(options=chrome_option)
        url = 'https://fanyi.baidu.com/translate#auto/zh/'
        self.driver.get(url)

    def translate_baidu(self, keywords):
        self.driver.find_element(By.ID, 'baidu_translate_input').clear()
        self.driver.find_element(By.ID, 'baidu_translate_input').send_keys(keywords)
        btn = self.driver.find_element(By.ID, 'translate-button')
        self.driver.execute_script("arguments[0].click();", btn)
        self.driver.find_element(By.CSS_SELECTOR, 'div > div > div.app-guide-aside > span').click()
        time.sleep(0.5)
        try:
            a = self.driver.find_element(By.XPATH, "//p[@class='ordinary-output target-output clearfix']")
            if a.text:
                print(f'翻译结果：{a.text}')
            else:
                print('抱歉，我还在学习该语种中...')
        except:
            print('抱歉，我还在学习该语种中...')

        self.driver.close()
